package chen.bupt.mapreduce.usermodel;

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import chen.bupt.util.HDFSFileUtils;

public class GetPCIReTopic {

	private static String author = "ballard";
	private static String outputPath = "/user/chenlingpeng/smth/user/";
	private static String inputPath = "/user/chenlingpeng/smth/user/";

	public static class Map1 extends Mapper<LongWritable, Text, Text, Text> {
		private static Text t = new Text("key");

		public void map(LongWritable key, Text value, Context context)
				throws IOException, InterruptedException {
			if (!HDFSFileUtils.isInputFile(context))
				return;
			if (value.toString().startsWith("1")) {
				context.write(t, value);
			}

		}
	}

	public static class Reduce1 extends Reducer<Text, Text, Text, NullWritable> {
		public void reduce(Text key, Iterable<Text> values, Context context)
				throws IOException, InterruptedException {
			int sum = 0;
			for (Text t : values) {
				sum++;
				context.write(t, NullWritable.get());
			}
			context.write(new Text("number:" + sum), NullWritable.get());
		}
	}

	/**
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {
		Configuration conf = new Configuration();
		Job job = new Job(conf, "GetpicReTopic");
		job.setJarByClass(GetPCIReTopic.class);
		job.setMapperClass(Map1.class);
		job.setReducerClass(Reduce1.class);
		job.setNumReduceTasks(1);
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(Text.class);
		Path input = new Path(inputPath+"last_month_topic_"+author);
		Path output = new Path(outputPath+author+"_retopic");
		HDFSFileUtils.deleteFile(output, conf);
		FileInputFormat.addInputPath(job, input);
		FileOutputFormat.setOutputPath(job, output);
		System.exit(job.waitForCompletion(true) ? 0 : 1);
	}

}
